<template>
  <div class="stock-list">
    <h2>股票列表</h2>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else>
      <el-table :data="stocks" height="500" style="width: 100%">
        <el-table-column prop="symbol" label="股票代码" min-width="120"></el-table-column>
        <el-table-column prop="name" label="公司名称" min-width="150"></el-table-column>
        <el-table-column prop="currentPrice" label="当前价格" min-width="120" align="right">
          <template #default="scope">
            ¥{{ scope.row.currentPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" fixed="right">
          <template #default="scope">
            <el-button @click="viewStockDetails(scope.row.symbol)" type="primary" size="small">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import apiService from '../services/ApiService';

const stocks = ref([]);
const loading = ref(false);
const error = ref(null);
const router = useRouter();

onMounted(async () => {
  await fetchStocks();
});

const fetchStocks = async () => {
  try {
    loading.value = true;
    error.value = null;
    const response = await apiService.getAllStocks();
    if (response.status==200) {
      stocks.value = response.data;
    } else {
      error.value = response.error || '获取股票数据失败';
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试';
    console.error('获取股票数据失败:', err);
  } finally {
    loading.value = false;
  }
};

const viewStockDetails = (symbol) => {
  // 验证股票代码
  const validation = apiService.validateStockSymbol(symbol);
  if (!validation.isValid) {
    alert(validation.error);
    return;
  }
  
  router.push(`/stocks/${symbol}`);
};
</script>

<style scoped>
.stock-list {
  padding: 20px;
}

.loading, .error {
  text-align: center;
  padding: 20px;
}

.error {
  color: red;
}
</style>